<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_store_order\Entity\ShusyStoreOrder;
use Drupal\shusy_store_order_address\Entity\ShusyStoreOrderAddress;
use Drupal\shusy_store_order_line\Entity\ShusyStoreOrderLine;
use Drupal\shusy_store_order_location\Entity\ShusyStoreOrderLocation;
use Drupal\shusy_store_order_validity\Entity\ShusyStoreOrderValidity;
use Exception;
use stdClass;

/**
 * @OA\Schema(
 *   schema="OrderPayment",
 *   type="object",
 *   description="OrderPayment",
 *   allOf={
 *       @OA\Schema(ref="#/components/schemas/OrderCart"),
 *   }
 * )
 */
class OrderPayment extends OrderCart {

  protected function setValue() {
    parent::setValue();
    if ($this->entity instanceof ShusyStoreOrder) {
      $validity = $this->getValidity($this->entity);
      $value = [
        /**
         * @OA\Property(
         *   property="address",
         *   type="object",
         *   description="选择的收货地址 如果没有选择地址返回 false",
         *   ref="#/components/schemas/AddressItem",
         * ),
         */
        'address' => $this->getAddress(),
        /**
         * @OA\Property(
         *   property="location",
         *   type="object",
         *   description="选择的经纬度地址 如果没有选择返回 false",
         *   ref="#/components/schemas/LocationItem",
         * ),
         */
        'location' => $this->getLocation(),
        /**
         * @OA\Property(
         *   property="note",
         *   type="string",
         *   description="订单备注",
         * ),
         */
        'note' => (string) $this->wrapper->note->value(),
        /**
         * @OA\Property(
         *   property="shipping",
         *   type="integer",
         *   description="配送方式 -1 未选择 0 到店自提 1 快达 2 快递",
         * ),
         */
        'shipping' => $shipping = $this->getShipping(),
        /**
         * @OA\Property(
         *   property="shippingLabel",
         *   type="string",
         *   description="配送方式文字",
         * ),
         */
        'shippingLabel' => $this->getShippingLabel($shipping),
        /**
         * @OA\Property(
         *   property="shippingList",
         *   type="array",
         *   description="此订单支持的配送方式",
         *   @OA\Items(ref="#/components/schemas/ShippingItem")
         * ),
         */
        'shippingList' => $this->getShippingList(),
        /**
         * @OA\Property(
         *   property="shipping_amount",
         *   type="number",
         *   description="配送费",
         * ),
         */
        'shipping_amount' => $this->convertYuan($this->getShippingAmount()),
        /**
         * @OA\Property(
         *   property="total",
         *   type="number",
         *   description="订单总价",
         * ),
         */
        'total' => $this->convertYuan($this->entity->total),
        /**
         * @OA\Property(
         *   property="totalAmount",
         *   type="integer",
         *   description="订单总价 分 用于特殊情况的计算",
         * ),
         */
        'totalAmount' => $this->entity->total,
        /**
         * @OA\Property(
         *   property="amount",
         *   type="number",
         *   description="还需要支付金额 快达拒绝后 重新支付时 可能为0",
         * ),
         */
        'amount' => $this->convertYuan($this->getAmount($this->entity)),
        /**
         * @OA\Property(
         *   property="validity",
         *   type="integer",
         *   description="支付有效期剩余秒数 待支付有效 其它状态忽略",
         * ),
         */
        'validity' => $validity,
        /**
         * @OA\Property(
         *   property="date",
         *   ref="#/components/schemas/Date",
         *   description="倒计时信息",
         * ),
         */
        'date' => Date::get(FALSE, FALSE, [$validity]),
        /**
         * @OA\Property(
         *   property="status",
         *   type="integer",
         *   description="订单状态 0 取消 1 购物车 2 待支付 3 待发货 4 待收货 5 待评价 6 已完成 7 未提交 10 拼团中",
         * ),
         */
        'status' => (int) $this->entity->status,
        /**
         * @OA\Property(
         *   property="statusLabel",
         *   type="string",
         *   description="状态标签 待支付 之类的文本",
         * ),
         */
        'statusLabel' => $this->getStatusLabel($this->entity),
        'coupon' => $this->getCoupon($this->entity),
        'gold' => $this->getGold($this->entity),
      ];
      $this->merge($value);
    }
  }

  /**
   * 获取可抵扣最大金额
   */
  protected function getMaxGold(ShusyStoreOrder $order) {
    $max = 0;
    $products = $order->products();
    foreach ($products as $line) {
      if ($line instanceof ShusyStoreOrderLine) {
        $lineWrapper = $line->wrapper();
        $gold = $lineWrapper->standard->gold->value();
        if ($gold) {
          $max += $line->total;
        }
      }
    }
    return $max;
  }

  protected function getGold(ShusyStoreOrder $order) {
    $max = $this->getMaxGold($order);
    $gold = points_get_total($this->getUid(), 'gold');
    $label = t("本订单最多可抵扣 @max¥", [
      '@gold' => $gold,
      '@amount' => $this->convertYuan($gold),
      '@max' => $this->convertYuan($max),
    ]);
    $lines = shusy_store_order_line_load_multiple(FALSE, [
      'store_order_id' => $order->id,
      'type' => 'gold',
    ]);
    if (!empty($lines)) {
      $line = reset($lines);
      if ($line instanceof ShusyStoreOrderLine) {
        $label = t("已抵扣 @amount¥", ['@amount' => $this->convertYuan($line->total)]);
      }
    }
    return ['label' => $label];
  }

  protected function getMyCoupon(int $uid, ShusyStoreOrder $order) {
    $query = db_select('shusy_store_coupon_hold', 'h');
    $query->fields('h', ['id']);
    $query->condition('uid', $uid);
    $query->condition('status', 0);
    $query->condition('store_id', [0, $order->store_id], 'IN');
    $dbAnd = db_and();
    $dbAnd->condition('validity_end', REQUEST_TIME, '>=');
    $query->condition($dbAnd);
    $query->condition('condition_min', $order->amount, '<');
    return $query->execute()->rowCount();
  }

  protected function getCoupon(ShusyStoreOrder $order) {
    $label = t("@number张优惠券可用.", ['@number' => $this->getMyCoupon($order->uid, $order)]);
    $lines = shusy_store_order_line_load_multiple(FALSE, [
      'store_order_id' => $order->id,
      'type' => 'coupon',
    ]);
    if (!empty($lines)) {
      $line = reset($lines);
      if ($line instanceof ShusyStoreOrderLine) {
        $label = t("@amount¥", ['@amount' => $this->convertYuan($line->total)]);
      }
    }
    return ['label' => $label];
  }

  protected function getAddress() {
    $address = $this->wrapper->address->value();
    if ($address instanceof ShusyStoreOrderAddress) {
      $tmp = new stdClass();
      $tmp->userName = $address->username;
      $tmp->telNumber = $address->telnumber;
      $tmp->nationalCode = $address->nationalcode;
      $tmp->provinceName = $address->provincename;
      $tmp->cityName = $address->cityname;
      $tmp->countyName = $address->countyname;
      $tmp->detailInfo = $address->detailinfo;
      return $tmp;
    }
    return FALSE;
  }

  protected function getLocation() {
    $address = $this->wrapper->location->value();
    if ($address instanceof ShusyStoreOrderLocation) {
      $tmp = new stdClass();
      $tmp->name = $address->name;
      $tmp->address = $address->address;
      $tmp->longitude = $address->longitude;
      $tmp->latitude = $address->latitude;
      return $tmp;
    }
    return FALSE;
  }

  protected function getShipping() {
    //配送方式 -1 未选择 0 到店自提 1 快达 2 快递
    try {
      $lines = $this->wrapper->lines;
      foreach ($lines as $line) {
        if ($line->type->value() == 'shipping') {
          $shipping_type = $line->shipping->shipping_type->value();
          switch ($shipping_type) {
            case 'shusy_service':
              return 0;
              break;
            case 'shusy_errand':
              return 1;
              break;
            case 'commerce_weight_shipping':
              return 2;
              break;
          }
        }
      }
    } catch (Exception $exception) {
      watchdog_exception(__FUNCTION__, $exception);
    }
    return -1;
  }

  protected function getShippingList() {
    $list = [];
    $shippings = shusy_store_order_shipping_type_options();
    $products = $this->value['products'];
    foreach ($products as $product) {
      $tmps = $product['shippings'];
      $shippings = array_intersect_key($shippings, $tmps);
    }
    foreach ($shippings as $shipping => $name) {
      switch ($shipping) {
        case 'commerce_weight_shipping':
          //检查店铺是否设置了运费模板
          $es = commerce_weight_shipping_load_multiple(FALSE, [
            'status' => 1,
            'store_id' => $this->entity->store_id,
          ]);
          if (!empty($es)) {
            $list[] = ShippingItem::init(FALSE, FALSE, ['物流服务', 2]);
          }
          break;
        case 'shusy_service':
          $list[] = ShippingItem::init(FALSE, FALSE, ['到店自提', 0]);
          break;
        case 'shusy_errand':
          $list[] = ShippingItem::init(FALSE, FALSE, ['快达服务', 1]);
          break;
      }
    }
    //到店服务", "快达服务", "物流服务
    $isService = $this->value['isService'];
    if ($isService) {
      $list = [];
      $list[] = ShippingItem::init(FALSE, FALSE, ['到店服务', 0]);
      return $list;
    }
    return $list;
  }

  //配送方式 -1 未选择 0 到店自提 1 快达 2 快递
  protected function getShippingLabel(int $shipping) {
    switch ($shipping) {
      case 0:
        $isService = $this->value['isService'];
        if ($isService) {
          return '到店服务';
        }
        return '到店自提';
      case 1:
        return '快达';
      case 2:
        return '快递';
    }
    return '请选择配送方式';
  }

  protected function getShippingAmount() {
    $lines = $this->wrapper->lines;
    foreach ($lines as $line) {
      if ($line->type->value() == 'shipping') {
        return $line->amount->value();
      }
    }
    return 0;
  }

  protected function getAmount(ShusyStoreOrder $order) {
    return shusy_store_order_pay_order_balance($order);
  }

  protected function getValidity(ShusyStoreOrder $order) {
    $es = shusy_store_order_validity_load_multiple(FALSE, ['store_order_id' => $order->id]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyStoreOrderValidity) {
        $t = $e->validity - REQUEST_TIME;
        return ($t > 0) ? $t : 0;
      }
    }
    return 0;
  }

  protected function getStatusLabel(ShusyStoreOrder $order) {
    return $order->getStatusOptions()[$order->status];
  }
}
